package com.djx.utils;

import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.djx.config.AliSmsConfiguration;
import lombok.SneakyThrows;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: SmsUtils
 * @Description: TODO
 * @author: 星~
 * @date: 2021/9/28 0028 上午 10:51
 */
public class SmsUtils {

    /**
     * 获取阿里云客户端
     *
     * @return
     */
    @SneakyThrows
    static com.aliyun.dysmsapi20170525.Client createClient(AliSmsConfiguration aliSmsConfiguration) {
        Config config = new Config()
                .setAccessKeyId(aliSmsConfiguration.getAccessKeyId())
                .setAccessKeySecret(aliSmsConfiguration.getAccessKeySecret());
        config.endpoint = aliSmsConfiguration.getEndpoint();
        return new com.aliyun.dysmsapi20170525.Client(config);
    }


    /**
     * 发送验证码
     *
     * @return
     */
    @SneakyThrows
    public static Map sendTheVerificationCode(String phone, String code,AliSmsConfiguration aliSmsConfiguration) {
        Map map = new HashMap();
        com.aliyun.dysmsapi20170525.Client client = SmsUtils.createClient(aliSmsConfiguration);
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        sendSmsRequest.setPhoneNumbers(phone).setTemplateCode(aliSmsConfiguration.getTemplateCode()).setTemplateParam("{\"code\":\"" + code + "\"}").setSignName(aliSmsConfiguration.getSignName());
        SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
        SendSmsResponseBody sendSmsResponseBody = sendSmsResponse.getBody();
        if (sendSmsResponseBody.getCode().equalsIgnoreCase("ok") && sendSmsResponseBody.getMessage().equalsIgnoreCase("ok")) {
            map.put("status", true);
            map.put("msg", "验证码发送成功");
            return map;
        }
        map.put("status", false);
        map.put("msg", sendSmsResponseBody.getMessage());
        return map;
    }


}